import Vue from 'vue'
// import {promiseApi} from '@/common/utils'
import {cloneDeep} from 'lodash'
import PERMISSION_MAP from '@/permission'

export const USER = 'USER'
export const UPDATE_USER = 'UPDATE_USER'
export const USER_LOGIN = 'USER_LOGIN'
export const USER_PERMISSION = 'USER_PERMISSION'
export const USER_LOGOUT = 'USER_LOGOUT'
export const LOGOUT = 'LOGOUT'
export const GET_CAPTCHA = 'GET_CAPTCHA'
export const GET_CODE = 'GET_CODE'
export const CHECK_CODE = 'CHECK_CODE'
export const FIND_PASSWORD = 'FIND_PASSWORD'
export const RESET_PASSWORD = 'RESET_PASSWORD'
export const DISPATCH_RECORD = 'DISPATCH_RECORD'
export const UPDATE_RECORD = 'UPDATE_RECORD'
export const GET_LIMITED_LIST = 'GET_LIMITED_LIST'
export const STORE_PERMISSION = 'STORE_PERMISSION'
export const UPDATE_DETAIL = 'UPDATE_DETAIL'
export const DISPATCH_DETAIL = 'DISPATCH_DETAIL'
export const EDIT_USERINFO = 'EDIT_USERINFO'
export const EDIT_USER = 'EDIT_USER'
const state = {
  account: null,
  token: null,
  list: null,
  permission: null,
  record: 0,
  detailStatus: 0,
  editUserData: []
}
const mutations = {
  [USER] (state, user) {
    state.account = user
  },
  [UPDATE_USER] (state, data) {
    state.account = data.user
    state.token = data.token
  },
  [UPDATE_RECORD] (state) {
    state.record += 1
  },
  [UPDATE_DETAIL] (state) {
    state.detailStatus += 1
  },
  [STORE_PERMISSION] (state, data) {
    state.permission = data
  },
  [EDIT_USERINFO] (state, data) {
    state.editUserData = data
  }
}

const actions = {
  [USER_LOGIN] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/login', _data, {
        headers: {
          'Content-Type': 'application/json',
          'api_login': true
        }
      }).then(res => {
        if (res.result) {
          // Vue.localStorage.set(Vue.const.COOKIE.KEY_USER, res.data, {
          //   maxAge: Vue.const.COOKIE.MAX_AGE
          // })
          Vue.localStorage.set(Vue.const.COOKIE.KEY_TOKEN, res.data.TOKEN, {
            maxAge: Vue.const.COOKIE.MAX_AGE
          })
          Vue.localStorage.set(Vue.const.COOKIE.KEY_MENU, res.data.menuList, {
            maxAge: Vue.const.COOKIE.MAX_AGE
          })
          Vue.localStorage.set(Vue.const.COOKIE.BUTTON_LIST, res.data.buttonList, {
            maxAge: Vue.const.COOKIE.MAX_AGE
          })
          document.cookie = `TOKEN=${res.data.TOKEN}`
          resolve(res)
          // if (res.success) {
          //   dispatch('USER_PERMISSION', {param: {}}).then(res => {
          //     resolve(res)
          //   })
          // } else {
          //   resolve(res)
          // }
        } else {
          resolve(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  [USER_PERMISSION] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/saas/permission/myResources.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        if (res.success) {
          let first = [{
            id: 'wbs0001',
            name: '首页',
            webUrl: 'dashboard',
            icon: 'fa fa-home',
            subResources: []
          }]
          if (res.data.resources) {
            res.data.resources.map(item => {
              if (Vue.localStorage.get(Vue.const.COOKIE.KEY_USER).superAdmin !== 1) {
                if (item.id === 'wbs0019') {
                  item.hidden = true
                }
              }
              if (item.id.match('fs')) { // 隐藏基金下级菜单
                item.subResources = []
              }
            })
            res.data.resources = first.concat(res.data.resources)
          } else {
            res.data.resources = first
          }
          Vue.localStorage.set(Vue.const.COOKIE.KEY_MENU, res.data, {
            maxAge: Vue.const.COOKIE.MAX_AGE
          })
          let permission = []
          for (let item in PERMISSION_MAP) {
            permission.push(PERMISSION_MAP[item])
          }
          Vue.localStorage.set(Vue.const.COOKIE.KEY_PERMISSION, permission, {
            maxAge: Vue.const.COOKIE.MAX_AGE
          })
          resolve(res)
        } else {
          resolve(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  [USER_LOGOUT] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/logout', _data, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.result) {
          // 置空USER状态
          // commit('UPDATE_USER', {user: null, token: null})
          Vue.localStorage.remove(Vue.const.COOKIE.KEY_TOKEN)
          Vue.localStorage.remove(Vue.const.COOKIE.KEY_USER)
          Vue.localStorage.remove(Vue.const.COOKIE.KEY_MENU)
          Vue.localStorage.remove(Vue.const.COOKIE.BUTTON_LIST)
          document.cookie = 'TOKEN=;  expires=Thu, 01 Jan 1970 00:00:01 GMT;'
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [LOGOUT] ({commit}) {
    // 置空USER状态
    commit('UPDATE_USER', {user: null, token: null})
    // 置空数据PERMISSION状态
    commit('STORE_PERMISSION', null)
    // 清除本地临时存储
    Vue.localStorage.remove(Vue.const.COOKIE.KEY_TOKEN)
    Vue.localStorage.remove(Vue.const.COOKIE.KEY_USER)
    Vue.localStorage.remove(Vue.const.COOKIE.KEY_MENU)
    Vue.localStorage.remove(Vue.const.COOKIE.KEY_PERMISSION)
  },

  [GET_CAPTCHA] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/common/captchaByUuid.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [GET_CODE] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/common/sendCheckCode.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [CHECK_CODE] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/common/checkAuthCode.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [FIND_PASSWORD] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/saas/findPassword.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [RESET_PASSWORD] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/http/saas/changePassword.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  [GET_LIMITED_LIST] ({commit, dispatch}, data) {
    let _data = cloneDeep(data)
    return new Promise((resolve, reject) => {
      Vue.req.post('/api/gwy/ex/entsysresource/getResBySystem.json', _data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  state,
  mutations,
  actions
}
